const cloud = require('wx-server-sdk')
cloud.init({
	// API 调用都保持和云函数当前所在环境一致
	env: cloud.DYNAMIC_CURRENT_ENV
})
const db=cloud.database()
const listDB = db.collection('list')
const userDB=db.collection("user")
const jwt = require('jsonwebtoken');
const option={
	algorithm:"HS256",
	expiresIn:"7day",
	issuer:"ChenBin"
}
const privateKey="ChenBin1786512286"
module.exports.add=async function(data){
	console.log("data  ",data);
	const token=data.token
	delete data.token
	console.log("token  ",token);
  	try{
		let user=jwt.verify(token ,privateKey,option)
		const {data:userRes}=await userDB.where({
			id:user.id,
			openid:user.openid
		}).get()
		console.log("userRes  ",userRes);
		if(userRes){
			data.id=user.id
			data.openid=user.openid
			data.state=1// 0发布中 1审核中 2审核失败 3违规内容 4过期内容3天下架一次需要重新审核
			const listRes=await listDB.add({data})
			return {
				code:0,
				msg:"发布成功",
				data:listRes._id
			}
		}else{
			return {
				code:400,
				msg:"用户不存在",
			}
		}
	}catch(err){
		return {
			code:400,
			msg:"登录状态过期",
		}
	}
}
module.exports.getList=async function(data){
	console.log("data  ",data);
	const sort=data.sort.rent
	const site=data.filter.site
	const houseType=data.filter.houseType
	console.log("site  ",site);
	const filter={}
	
	if(houseType.room){
		filter.room=houseType.room
	}
	if(houseType.hall){
		filter.hall=houseType.hall
	}
	if(houseType.kitchen){
		filter.kitchen=houseType.kitchen
	}
	if(houseType.restRoom){
		filter.restRoom=houseType.restRoom
	}
	let where={
		areaValue:site,
		...filter
	}
	console.log("where  ",where);
	
	if(sort===0){
		const {data:list} = await listDB.where(where).skip(data.skip).limit(data.limit).field({openid: false}).get()

		if(list.length===0){
			return {
				code:400,
				msg:"没有更多信息",
				list
			}
		}
		return {
			code:0,
			msg:"获取到了列表",
			list
		}
	}else{
		const _ = db.command
		const {data:list} = await listDB.where(where).skip(data.skip).limit(data.limit).sort({
			rent: sort
		}).field({openid: false}).get()
		if(list.length===0){
			return {
				code:400,
				msg:"没有更多信息",
				list
			}
		}
		return {
			code:0,
			msg:"获取到了列表",
			list
		}
	}
	// const {data:list}=await listDB.field({
		
	// 	openid: false,
	// }).get()
	// const {data:list} = await listDB.where({
	// 	// rent: _.eq("500")//筛选 全等
	// 	// rent: _.lt(500)//筛选 小于
	// 	rent: _.gt(500)//筛选 大于
	// }).get()
}

module.exports.getListHome=async function(){
	const {data:list}=await listDB.limit(5).field({openid: false}).get()
	
	return {
		code:0,
		list,
		msg:"成功"
	}
}
module.exports.details=async function(data){
	const {data:list}=await listDB.doc(data._id).get()
	return {
		code:0,
		list,
		msg:"获取详情"
	}	
}